<template>
  <el-container class="home-container">
    <!-- 首页侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '200px'">
      <!-- logo 名称 -->
      <div :class="['logo', isCollapse ? '' : '']">
        <span>SIK</span>
        <transition name="h1"
          ><h1 v-show="!isCollapse">博客管理系统</h1></transition
        >
      </div>
      <el-scrollbar>
        <el-menu
          router
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          :unique-opened="false"
          :collapse="isCollapse"
          :collapse-transition="false"
          :default-active="$route.path"
        >
          <el-menu-item index="/admin/dashboard">
            <i class="el-icon-house"></i>
            <template #title>
              <span>首页</span>
            </template>
          </el-menu-item>
          <el-submenu index="/admin/article">
            <!-- <template v-slot:title> v-slot: 可以简写成 #-->
            <template #title>
              <i class="el-icon-document-copy"></i>
              <span>文章管理</span>
            </template>
            <el-menu-item index="/admin/article">
              <i class="el-icon-document"></i>
              文章列表
            </el-menu-item>
            <el-menu-item index="/admin/category">
              <i class="el-icon-files"></i>
              分类管理
            </el-menu-item>
          </el-submenu>
          <el-menu-item index="/admin/user">
            <i class="el-icon-user"></i>
            <template v-slot:title>
              <span>用户管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/admin/comments">
            <i class="el-icon-message"></i>
            <template v-slot:title>
              <span>评论管理</span>
            </template>
          </el-menu-item>
        </el-menu>
      </el-scrollbar>
    </el-aside>

    <el-container>
      <!-- 首页头部 -->
      <el-header>
        <i
          :class="['el-icon-s-fold', isCollapse ? 'isCollapse' : '']"
          @click="isCollapse = !isCollapse"
        ></i>
        <!-- 头部nav图标 -->
        <div class="right_menu">
          <el-tooltip
            class="item"
            effect="dark"
            content="门户页面"
            placement="bottom"
          >
            <span>
              <i class="el-icon-s-promotion" @click="handleLink"></i
            ></span>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="上传头像"
            placement="bottom"
          >
            <span>
              <i class="el-icon-upload" @click="dialogShow = true"></i
            ></span>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="修改密码"
            placement="bottom"
          >
            <span
              ><i class="el-icon-lock" @click="dialogFormVisible = true"></i
            ></span>
          </el-tooltip>
          <el-dropdown trigger="click">
            <span class="avatar">
              <el-avatar
                :size="40"
                :src="imagesUrl == null ? '/avatar.jpg' : imagesUrl"
              ></el-avatar>
              <i class="el-icon-caret-bottom"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <i class="el-icon-house"></i>
                  首页</el-dropdown-item
                >
                <el-dropdown-item divided @click.native.prevent="logout">
                  <i class="el-icon-switch-button"></i>
                  退出登录</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <!-- 首页主体部分 -->
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
    <!-- 弹出框--修改密码 -->
    <el-dialog
      title="修改密码"
      :visible.sync="dialogFormVisible"
      @close="handleClosePwd"
    >
      <el-form ref="updatePwd" :model="pwdForm" :rules="pwdRules">
        <el-form-item
          label="旧密码"
          :label-width="formLabelWidth"
          prop="oldPwd"
        >
          <el-input v-model="pwdForm.oldPwd" show-password></el-input>
        </el-form-item>
        <el-form-item
          label="新密码"
          :label-width="formLabelWidth"
          prop="newPwd"
        >
          <el-input v-model="pwdForm.newPwd" show-password></el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          :label-width="formLabelWidth"
          prop="confirmPwd"
        >
          <el-input v-model="pwdForm.confirmPwd" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 弹出框--上传头像 -->
    <el-dialog
      title="上传头像"
      :visible.sync="dialogShow"
      @close="handleCloseAvatar"
    >
      <el-upload
        class="upload-demo"
        drag
        action=" "
        list-type="picture"
        :limit="1"
        show-file-list
        :auto-upload="false"
        :on-change="handleChange"
        ref="uploadPic"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="handleUpload">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
// 导入验证规则
import { regPassword, password } from "@/utils/validata";
export default {
  name: "Home",
  created() {
    // 获取头像
    // const id = this.$route.params.id;
    const id = sessionStorage.getItem("id");
    // 发送请求
    this.$http.get(`/users/avatar/${id}`).then((res) => {
      if (res.code == 0) {
        // console.log(res);
        this.imagesUrl = `http://127.0.0.1:3000/${res.result.avatar}`;
      } else {
        this.$message({
          type: "error",
          message: res.msg,
          duration: 1000,
        });
      }
    });
  },
  data() {
    // 验证密码表单数据
    const validatePassword = (rule, value, callback) => {
      if (!regPassword(value)) {
        callback(new Error("密码必须由6到11位大小写字母和数字组成"));
      } else {
        callback();
      }
    };
    const validatePassword1 = (rule, value, callback) => {
      if (value !== this.pwdForm.newPwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      // 路径
      isCollapse: false,
      // 控制头像弹出框
      dialogShow: false,
      // 控制密码弹出框
      dialogFormVisible: false,
      // 保存上传的头像文件
      dataList: [],
      // 保存头像路径
      imagesUrl: "",
      pwdForm: {
        oldPwd: "",
        newPwd: "",
        confirmPwd: "",
      },
      // 控制label宽度
      formLabelWidth: "100px",
      pwdRules: {
        oldPwd: [...password, { validator: validatePassword, trigger: "blur" }],
        newPwd: [...password, { validator: validatePassword, trigger: "blur" }],
        confirmPwd: [
          ...password,
          { validator: validatePassword, trigger: "blur" },
          { validator: validatePassword1, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    // 退出登录
    logout() {
      // 1.删除localStorage中token
      localStorage.removeItem("token");
      // 2.跳转路径
      this.$message.success({
        type: "success",
        message: "退出登录成功",
        duration: 1000,
      });
      this.$router.push("/login");
    },
    // 密码弹出框关闭时调用
    handleClosePwd() {
      // 重置表单和验证
      this.$refs.updatePwd.resetFields();
    },
    // 修改密码
    handleConfirm() {
      // console.log(this.$route.params.id)
      // 获取登录管理员id
      // const id = this.$route.params.id;
      const id = sessionStorage.getItem("id");
      this.$refs.updatePwd.validate((valid) => {
        if (valid) {
          // 1.发送请求/POST/oldPwd,confirmPwd
          this.$http
            .put(`/users/updatePwd/${id}`, {
              oldPwd: this.pwdForm.oldPwd,
              newPwd: this.pwdForm.confirmPwd,
            })
            .then((res) => {
              if (res.code == 0) {
                this.dialogFormVisible = false;
                // 2.提示消息
                this.$message({
                  type: "success",
                  message: "修改密码成功,请重新登录",
                  duration: 1500,
                });
                // 3.跳转页面
                localStorage.removeItem("token");
                this.$router.push("/login");
              } else {
                this.$message({
                  type: "error",
                  message: res.msg,
                  duration: 1000,
                });
              }
            });
        } else {
          this.$message({
            type: "error",
            message: "密码不合法,请重新输入!",
            duration: 1000,
          });
        }
      });
    },
    // 关闭上传文件列表
    handleCloseAvatar() {
      this.$refs.uploadPic.clearFiles();
    },

    // 上传的文件改变时的回调,(在添加文件、上传成功和上传失败时都会被调用)
    handleChange(file, fileList) {
      // console.log(file);
      // console.log(fileList);
      // 把上传文件添加到dataList
      this.dataList.push(file.raw);
      // console.log(this.dataList);
    },
    // 上传头像
    handleUpload() {
      // 获取管理员id
      // const id = this.$route.params.id;
      const id = sessionStorage.getItem("id");
      // 创建表单对象
      const formData = new FormData();
      // 判断是否上传了图片，如果上传了图片，将图片存入到formData中
      if (this.dataList) {
        formData.append("avatar", this.dataList[0]);
      }
      // console.log(formData.get("avatar"));
      // 关闭弹窗
      this.dialogShow = false;

      // 发送请求,post/文件对象/form-data格式
      this.$http
        .put(`/users/uploadPic/${id}`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          if (res.code == 0) {
            // 上传成功
            // console.log(res.result.avatar);
            this.imagesUrl = `http://127.0.0.1:3000/${res.result.avatar}`;
            this.$message({
              type: "success",
              message: res.msg,
              duration: 1000,
            });
          } else {
            this.$message({
              type: "error",
              message: "服务器错误,请稍后重试",
              duration: 1000,
            });
          }
        });
    },
    handleLink() {
      location.href = "http://localhost:8080/home/article";
    },
  },
};
</script>
<style lang="stylus">
.home-container
  &>.el-dialog__wrapper
    &>.el-dialog
      width: 500px
      .el-form-item
        width: 425px
</style>

<style lang="stylus" scoped>
// 头像
.home-container
  .el-avatar
    &>>>img
      width: 40px;
      cursor: pointer
  //  弹出框
  &>>>.el-dialog
    .el-form-item
      .el-form-item__label
        font-weight:700
    // 上传文件
    .el-upload
      display: block
      .el-upload-dragger
        margin: 0 auto
    .el-upload__tip
      font-size:14px
      text-align: center
      margin-top: 15px
</style>
<style lang="stylus" scoped>
@import '~@/assets/styles/animation.styl'
/* 由postCSS库，提供深度作用选择器语法 */
.home-container
  height: 100vh;
  .el-aside
    transition: width 0.4s
    background: #304156;
    user-select: none;
    /* 使用>>>深度选择器 */
    .el-scrollbar
      height: calc(100% - 60px);
      & >>> .el-scrollbar__wrap
        overflow-x: hidden;
      /* 不显示水平方向的滚动条 */
      & >>> .el-scrollbar__bar.is-horizontal
        display: none;
      .el-menu
        border-right: 0;
        i
          color:#BFCBCF
    .logo
      display: flex;
      height: 60px;
      justify-content: space-evenly;
      align-items: center;
      color: #fff;
      background: #1f2d3d;
      span
        font-size: 20px;
        color: #6495ED
      h1
        font-size: 18px;
        font-weight:700
  .el-header
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    &>i
      font-size: 24px;
      color: #333;
      cursor: pointer;
      transition: all 0.3s;
      &:hover
        color: #6495ED
    .isCollapse
      transform: rotate(-180deg);
    .right_menu
      display: flex
      justify-content: space-evenly
      align-items: center
      .el-tooltip
        i
          font-size:22px
          color: #5a5e66
          cursor: pointer
          padding: 0 10px
          &:hover
            color: #6495ED
      .el-dropdown
        i
          font-size: 12px;
          color: #5a5e66;
  .el-main
    background: #edeff2;
    min-width: 800px;
</style>
